package com.example.securitydemo.config;

import com.example.securitydemo.service.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;



@Configuration     // 自动配置
@EnableWebSecurity // 支持Spring Security

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailServiceImpl userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {


//         auth.inMemoryAuthentication()
//                 .withUser("admin")
//                 .password(passwordEncoder().encode("123"))
//                 .roles("admin");


        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        //使用UserDetailsService进行身份认证
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);


    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义用户访问控制
        http.authorizeHttpRequests().antMatchers("/")    //开启Ant风格路径匹配
                .permitAll()   //无条件对请求放行
                .antMatchers("/detail/common/**").hasRole("common")
                .antMatchers("/detail/vip/**").hasRole("vip")
                .anyRequest().authenticated()   //匹配任何请求,匹配已经登录认证的用户
                .and()//功能的连接符
                .formLogin();    //基于表单的用户登录

        //自定义用户登录控制
        http.formLogin().loginPage("/userLogin").permitAll().usernameParameter("name")
                .passwordParameter("pwd").defaultSuccessUrl("/")
                .failureUrl("/userLogin?error");

        //自定义用户登出
        http.logout().logoutUrl("/mylogout").logoutSuccessUrl("/");



        //关闭CSRF防护功能（Spring Security默认开启防护功能）
        http.csrf().disable();   //不推荐
    }


    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密码
        return new BCryptPasswordEncoder();
    }
}
